package com.yedean.factory.context.annotation;

import cn.hutool.core.util.StrUtil;
import com.yedean.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.yedean.factory.config.BeanDefinition;
import com.yedean.factory.support.BeanDefinitionRegistry;

import java.util.Set;

public class ClasspathBeanDefinitionScanner extends ClasspathScanningCandidateComponentProvider{
    
    private BeanDefinitionRegistry registry;

    public ClasspathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }
    
    public void doScan(String... basePackages){

        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            //扫描scope注解
            candidates.forEach(x->{
                String scope = resolveBeanScope(x);
                if (StrUtil.isNotEmpty(scope)){
                    x.setScope(scope);
                }
                registry.registerBeanDefinition(determineBeanName(x),x);
            });
        }
        
        registry.registerBeanDefinition("internalAutowiredAnnotationProcessor",new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class));
    }
    
    
    
    private String resolveBeanScope(BeanDefinition definition){
        Class<?> beanClass = definition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if (null!=scope){
            return scope.value();
        }
        return StrUtil.EMPTY;
    }
    
    public String determineBeanName(BeanDefinition definition){
        Class<?> beanClass = definition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        String value = component.value();
        if (StrUtil.isEmpty(value)){
            return StrUtil.lowerFirst(beanClass.getSimpleName());
        }
        return value;
    }
}
